package com.tornado.community.controller;

import com.tornado.community.dto.NotificationDto;
import com.tornado.community.mapper.custome.MyQuestionMapper;
import com.tornado.community.model.Question;
import com.tornado.community.model.User;
import com.tornado.community.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class ProfileController {
    private final MyQuestionMapper myQuestionMapper;
    private final NotificationService notificationService;

    @Autowired
    public ProfileController(MyQuestionMapper myQuestionMapper,NotificationService notificationService) {
        this.myQuestionMapper = myQuestionMapper;
        this.notificationService = notificationService;
    }

    @GetMapping("/profile/{action}")
    public String profile(@PathVariable(name = "action") String action, Model model,
                          @RequestParam(name = "page", defaultValue = "1") Integer page,
                          @RequestParam(name = "size", defaultValue = "5") Integer size,
                          HttpSession session) {
        model.addAttribute("page", page);
        model.addAttribute("pageCount", 0);
        User user = (User) session.getAttribute("user");
        if ("question".equals(action)) {
            model.addAttribute("section", "question");
            model.addAttribute("sectionName", "我的提问");
            List<Question> questionList = myQuestionMapper.selectQuestionListByCreator(user.getId(), size * (page - 1), size);
            double pageCount = (myQuestionMapper.countByCreator(user.getId()) * 1.0) / size;
            model.addAttribute("questionList", questionList);
            model.addAttribute("pageCount", (int) Math.ceil(pageCount));
        }
        if ("replies".equals(action)) {
            model.addAttribute("section", "replies");
            model.addAttribute("sectionName", "最新回复");
            int unread = notificationService.unreadCount(user.getId());
            List<NotificationDto> notificationDtoList = notificationService.selectNotificationList(user.getId());
            model.addAttribute("unreadCount", unread);
            model.addAttribute("notificationDtoList", notificationDtoList);
        }
        return "profile";
    }
}
